package com.oracle.shiro;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.oracle.comment.Constants;
/*import com.oracle.pojo.SysAuthority;
import com.oracle.pojo.SysRole;*/
import com.oracle.pojo.Role;
import com.oracle.pojo.User;
/*import com.oracle.service.RoleService;*/
import com.oracle.service.RoleService;
import com.oracle.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.util.StringUtils;


/**
 * 
* @ClassName: UserRealm 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author Jencks 
* @date 2017年4月23日 下午10:53:43 
*
 */
public class UserRealm extends AuthorizingRealm {
	// 用户对应的角色信息与权限信息都保存在数据库中，通过UserService获取数据
	@Resource
    private UserService userService;
	@Resource
	private RoleService roleService;

    /**
     * 提供用户信息返回权限信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    	String currentUsername = (String)super.getAvailablePrincipal(principals);
		List<String> roleList = new ArrayList<String>();
		/*List<String> permissionList = new ArrayList<String>();*/
		//从数据库中获取当前登录用户的详细信息
		User user = userService.findUserByUserName(currentUsername);
		if(null != user){
			/*List<SysAuthority> authorities = userService.getPermissions(user.getId());*/
			List<Role> sysRoles = roleService.findRolesByUserID(user.getId());
			/*//实体类Role中包含有角色权限的实体类信息
			if(null!= authorities && authorities.size()>0){
				//获取权限
				for(SysAuthority pmss : authorities){
					if(pmss!=null && !StringUtils.isEmpty(pmss.getAuthorityCode())){
						permissionList.add(pmss.getAuthorityCode());
					}
				}
			}*/
			if(null!= sysRoles && sysRoles.size()>0){
				//获取当前登录账号的角色权限
				for(Role sr : sysRoles){
					if(sr!=null && !StringUtils.isEmpty(sr.getRoleCode())){
						roleList.add(sr.getRoleCode());
					}
				}
			}
		}else{
			throw new AuthorizationException();
		}
		//为当前用户设置角色和权限
		SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
		simpleAuthorInfo.addRoles(roleList);
		/*simpleAuthorInfo.addStringPermissions(permissionList);*/
		return simpleAuthorInfo;
    }

    /**
     * 提供账户信息返回认证信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
			String username = (String) token.getPrincipal();
			User user = userService.findUserByUserName(username);
			if (user == null) {
			    // 用户名不存在抛出异常
			    throw new UnknownAccountException();
			}else{
				ByteSource salt = ByteSource.Util.bytes(user.getSalt());//盐值
//				SimpleHash sh = new SimpleHash("MD5", user.getUserPwd(), salt, 1024);
				SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getPhone(),
						user.getPassWord(),salt,getName());
				this.setSession(Constants.CURRENT_USER, user);
				return authenticationInfo;
			}
			
    }
    
	/**
	 * 将一些数据放到ShiroSession中,以便于其它地方使用
	 * 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到
	 */
	private void setSession(Object key, Object value){
		Subject currentUser = SecurityUtils.getSubject();
		if(null != currentUser){
			Session session = currentUser.getSession();
			System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");
			if(null != session){
				session.setAttribute(key, value);
			}
		}
	}
    
    
}